package com.app.shortvideo.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.app.shortvideo.databinding.ActivityMainBinding
import com.app.shortvideo.base.BaseActivity
import com.app.shortvideo.base.BaseFragment
import com.app.shortvideo.ui.main.HomeFourFragment
import com.app.shortvideo.ui.main.HomeOneFragment
import com.app.shortvideo.ui.main.HomeThreeFragment
import com.app.shortvideo.ui.main.HomeTwoFragment
import com.app.library.base.LibViewModel
import com.app.shortvideo.module.DataModule
import com.app.library.widget.BottomBarItem
import com.app.library.widget.BottomBarLayout
import com.app.shortvideo.ui.viewmodel.BaseViewModel
import com.hjq.toast.Toaster
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding, BaseViewModel>()
    ,BottomBarLayout.OnItemSelectedListener{
    companion object {
        fun startMain(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }
    private var mFragments: ArrayList<BaseFragment<*, *>> = ArrayList()
    override fun initData(savedInstanceState: Bundle?) {
    }

    override fun initView() {
        initViewPager()
        CoroutineScope(Dispatchers.IO).launch {
            val userInfo = DataModule().provideUserInfo()
            Toaster.show(userInfo.userName)
        }

    }
    private fun initViewPager() {
        mFragments.add(HomeOneFragment.newInstance())
        mFragments.add(HomeTwoFragment.newInstance())
        mFragments.add(HomeThreeFragment.newInstance())
        mFragments.add(HomeFourFragment.newInstance())
        binding.mViewPager.isUserInputEnabled = false
        binding.mViewPager.adapter = (object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return mFragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return mFragments[position]
            }
        })
        binding.mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.mBottomBarLayout.currentItem = position
            }
        })
        binding.mBottomBarLayout.setOnItemSelectedListener(this)
    }

    override fun onItemSelected(
        bottomBarItem: BottomBarItem?,
        previousPosition: Int,
        currentPosition: Int
    ) {
        binding.mViewPager.setCurrentItem(currentPosition,false)
    }


}